package file;

import java.io.*;
import java.util.Scanner;

//查找文件名或者文件内容是否存在用户指定的关键字，并打印出来
public class Demo3 {
    public static void main(String[] args) throws IOException {
        System.out.println("请输入你要搜索的目录：");
        Scanner scan  = new Scanner(System.in);
        String findDirectory = scan.next();
        File file = new File(findDirectory);
        if(!file.isDirectory()) {
            System.out.println("该目录不存在或者该目录输入有误...");
            return;
        }
        System.out.println("请输入指定关键字：");
        String token = scan.next();
        scanFile(file, token);
    }

    private static void scanFile(File rootFile, String token) throws IOException {
        File[] files = rootFile.listFiles();
        for(File file : files) {
            if(file.isDirectory()) {
                scanFile(file, token);
            } else {
                checkFile(file, token);
            }
        }
    }

    private static void checkFile(File file, String token) throws IOException {
        if(file.getName().contains(token)) {
            System.out.println("该文件名包含关键字：" + file.getAbsolutePath());
        }
        //字符流读
        try(Reader reader = new FileReader(file)) {
            StringBuilder stringBuilder = new StringBuilder();
            char[] b = new char[1024];
            while(true) {
                int n = reader.read(b);
                if(n == -1) {
                    break;
                }
                stringBuilder.append(b,0,n);
            }
            if(stringBuilder.toString().contains(token)) {
                System.out.println("文件内容包含关键字：" + file.getAbsolutePath());
            }
        }
    }
}
